from model.Student import Student
from controller.Base import BaseHandler
from tornado import gen


# m : method
class StudentHandler(BaseHandler):
    @gen.coroutine
    def get(self):
        try:
            method = self.get_argument("m")
        except Exception as e:
            return self.write(self.response_code.PARAM_NOT_COMPLETE)

        # 类型检查
        if not method.isdigit():
            return self.write(self.response_code.PARAM_TYPE_BIND_ERROR)
        method = int(method)
        t = self.response_code.SUCCESS.copy()
        if method == 1:
            # 按页获取所有学生
            try:
                page_num = self.get_argument("page")
            except Exception as e:
                return self.write(self.response_code.PARAM_NOT_COMPLETE)
            data = yield Student.get_all(page_num)
            count = yield Student.get_count()
        elif method == 0:
            # 通过学号查找学生
            try:
                s_id = self.get_argument("id")
            except Exception as e:
                return self.write(self.response_code.PARAM_NOT_COMPLETE)
            data = yield Student.get_by_id(s_id)
            data = (data,)
            count = 1
        else:
            return self.write(self.response_code.PARAM_IS_INVALID)
        t["data"] = data
        t["total"] = count
        return self.write(t)

    @gen.coroutine
    def post(self):
        try:
            id = self.get_argument("id")
            name = self.get_argument("name")
            class_id = self.get_argument("class")
            pid = self.get_argument("pid")
        except Exception as e:
            return self.write(self.response_code.PARAM_NOT_COMPLETE)

        result = yield Student.add(id, name, class_id, pid)
        if result:
            self.write(self.response_code.SUCCESS)
        else:
            self.write(self.response_code.USER_HAS_EXISTED)

    @gen.coroutine
    def put(self):
        pass

    @gen.coroutine
    def delete(self):
        try:
            s_id = self.get_argument("id")
        except Exception as e:
            return self.write(self.response_code.PARAM_NOT_COMPLETE)
        result = Student.del_by_id(s_id)
        if result:
            self.write(self.response_code.SUCCESS)
        else:
            self.write(self.response_code.USER_NOT_EXIST)

